<?

class LoggerGeoIP
{
    protected static $operable;
    protected static $geoip;
    private $lastIP;
    private $lastRecord;

    public function __construct() 
    {
        $geoipDatFile   = dirname(__FILE__) . '/geoip/geoipcity.dat';
        $geoipDatUrl    = 'compress.zlib://http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz';
        $geoipInc       = dirname(__FILE__) . '/geoip/geoipcity.inc';

        if (!isset(self::$geoip))
        {
            self::$operable = false;
            require_once($geoipInc);

            if (file_exists($geoipDatFile))
            {
                if (LoggerConfig::$updateExtDatabases && is_writable($geoipDatFile))
                {
                    $fileMTime = @filemtime($geoipDatFile);
                    if ($fileMTime !== false && $fileMTime < (time() - 30*24*3600))
                    {
                        $fromFp = @fopen($geoipDatUrl, 'rb');
                        if ($fromFp)
                        {
                            $toFp = @fopen($geoipDatFile, 'wb');
                            if ($toFp)
                            {
                                while (!feof($fromFp))
                                {
                                    fwrite($toFp, fread($fromFp, 1024*1024));
                                }
                                fclose($toFp);
                            }
                            fclose($fromFp);
                        }
                    }
                }

                self::$geoip = geoip_open($geoipDatFile, GEOIP_STANDARD);
                self::$operable = true;
            }
        }
    }

    public function operable()
    {
        return self::$operable;
    }

    public function getData($ip)
    {
        if (!self::$operable)
            return false;

        if (isset($this->lastIP) && $this->lastIP === $ip)
        {
            $record = $this->lastRecord;
        }
        else
        {
            $record = geoip_record_by_addr(self::$geoip, $ip);
            $this->lastIP = $ip;
            $this->lastRecord = $record;
        }

        if (!is_object($record))
            return false;

        return array(
            'country' => $record->country_name,
            'city' => $record->city
        );
    }
}
